package struct;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import struct.enums.State;

import java.util.List;

public class AppInfo {
    public static final String APP_NAME_FIELD = "app_name";
    private static final String CTX_FIELD = "ctx";
    private static final String INV_FIELD = "inv";
    private static final String APP_STATE_FIELD = "state";
    private static final String SENSORS_FIELD = "sensors";
    private static final String ACTORS_FIELD = "actors";

    public String name;
    public boolean ctx;
    public boolean inv;
    public State state;
    public List<String> sensors;
    public List<String> actors;
    private JSONObject jo;

    public AppInfo(String name, boolean ctx, boolean inv, State state, List<String> sensors, List<String> actors) {
        this.name = name;
        this.ctx = ctx;
        this.inv = inv;
        this.state = state;
        this.sensors = sensors;
        this.actors = actors;
    }

    public AppInfo(JSONObject obj) {
        this.jo = obj;
        this.name = obj.getString(APP_NAME_FIELD);
        this.ctx = obj.getBoolean(CTX_FIELD);
        this.inv = obj.getBoolean(INV_FIELD);
        this.state = State.fromString(obj.getString(APP_STATE_FIELD));
        this.sensors = obj.getJSONArray(SENSORS_FIELD).toJavaList(String.class);
        this.actors = obj.getJSONArray(ACTORS_FIELD).toJavaList(String.class);
    }

    @Override
    public String toString() {
        if (jo != null)
            return jo.toJSONString();

        jo = new JSONObject();
        jo.put(APP_NAME_FIELD, name);
        jo.put(CTX_FIELD, ctx);
        jo.put(INV_FIELD, inv);
        jo.put(APP_STATE_FIELD, state);
        JSONArray ja = new JSONArray();
        ja.addAll(sensors);
        jo.put(SENSORS_FIELD, ja);
        ja = new JSONArray();
        ja.addAll(actors);
        jo.put(ACTORS_FIELD, ja);
        return jo.toJSONString();
    }
}
